<template>
  <div class="chat-container">
    <!-- 左侧会话列表 -->
    <div class="chat-sidebar">
      <div class="sidebar-content">
        <a-list
          class="chat-list"
          :data-source="chatList"
          :loading="loading"
        >
          <template #header>
            <div class="chat-list-header">
              <span class="header-title">会话列表</span>
              <a-button type="primary" @click="createNewChat" size="big">
                <template #icon><plus-outlined /></template>
                新建会话
              </a-button>
            </div>
          </template>
          <template #renderItem="{ item }">
            <a-list-item
              :class="{ 'active': currentChatId === item.sessionId }"
              @click="switchChat(item)"
              class="chat-item"
            >
              <template #extra>
                <a-button type="text" @click.stop="deleteChat(item)" class="delete-btn">
                  <template #icon><delete-outlined /></template>
                </a-button>
              </template>
              <a-list-item-meta>
                <template #title>
                  <span class="chat-title">{{ item.title }}</span>
                </template>
                <template #description>
                  <span class="chat-message">{{ item.lastMessage }}</span>
                </template>
              </a-list-item-meta>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </div>

    <!-- 右侧对话区域 -->
    <div class="chat-main">
      <!-- 顶部导航栏 -->
      <div class="chat-header">
        <div class="chat-title">
          <a-space>
            <a-avatar :size="40" class="ai-avatar">
              <template #icon><robot-outlined /></template>
            </a-avatar>
            <div class="title-content">
              <h3>AI 智能助手</h3>
              <p class="subtitle">随时为您提供智能对话服务</p>
            </div>
          </a-space>
        </div>
        <div class="header-actions">
          <a-space>
            <a-button type="text" class="share-btn">
              <template #icon><share-alt-outlined /></template>
            </a-button>
            <a-button type="text" class="more-btn">
              <template #icon><ellipsis-outlined /></template>
            </a-button>
          </a-space>
        </div>
      </div>

      <!-- 对话内容区域 -->
      <div class="chat-content">
        <!-- 快捷主题和设计指南 -->
        <div class="topic-tabs" v-if="showTopicGuides">
          <div class="do-you-want">Do you want?</div>

          <a-row :gutter="16">
            <a-col :span="12">
              <div class="topic-section">
                <div class="topic-header">
                  <fire-outlined />
                  <span>Hot Topics</span>
                </div>
                <div class="topic-content">
                  <a-list :data-source="hotTopics" size="small">
                    <template #renderItem="{ item }">
                      <a-list-item @click="selectTopic(item)" class="topic-item">
                        {{ item.title }}
                      </a-list-item>
                    </template>
                  </a-list>
                </div>
              </div>
            </a-col>
            <a-col :span="12">
              <div class="topic-section">
                <div class="topic-header">
                  <read-outlined />
                  <span>Design Guide</span>
                </div>
                <div class="topic-content">
                  <a-list :data-source="designGuides" size="small">
                    <template #renderItem="{ item }">
                      <a-list-item @click="selectGuide(item)" class="topic-item">
                        <a-space>
                          <component :is="item.icon" />
                          <span>{{ item.title }}</span>
                        </a-space>
                      </a-list-item>
                    </template>
                  </a-list>
                </div>
              </div>
            </a-col>
          </a-row>
        </div>

        <!-- 对话内容区域 -->
        <div class="chat-messages" ref="messageContainer">
          <BubbleList
            :roles="roles"
            :style="{ maxHeight: '600px' }"
            :items="currentMessages.map(({ id, role, content }) => ({
              key: id,
              role: role === 'user' ? 'user' : 'ai',
              content
            }))"
          />
        </div>

        <!-- 底部操作区域 -->
        <div class="chat-bottom">
          <!-- 快捷操作按钮 -->
          <div class="quick-actions">
            <a-space>
              <a-button type="text" @click="selectHotTopics">
                <template #icon><fire-outlined /></template>
                Hot Topics
              </a-button>
              <a-button type="text" @click="selectDesignGuide">
                <template #icon><read-outlined /></template>
                Design Guide
              </a-button>

            </a-space>
          </div>

          <!-- 输入区域 -->
          <div class="chat-input">
            <div class="input-tools">
              <a-space>
                <a-button type="text" class="tool-btn">
                  <template #icon><smile-outlined /></template>
                </a-button>
                <a-upload
                  :file-list="fileList"
                  :multiple="true"
                  action="/api/upload"
                  @change="handleUploadChange"
                  :show-upload-list="false"
                >
                  <a-button type="text" class="tool-btn">
                    <template #icon><paper-clip-outlined /></template>
                  </a-button>
                </a-upload>
              </a-space>
            </div>
            <a-input-group compact class="input-group">
              <a-textarea
                v-model:value="inputMessage"
                :rows="3"
                placeholder="请输入您的问题..."
                @keypress.enter.prevent="sendMessage"
                class="message-input"
                :bordered="false"
                :auto-size="{ minRows: 1, maxRows: 5 }"
              />
              <a-button
                type="primary"
                :loading="sending"
                @click="sendMessage"
                class="send-button"
                shape="circle"
              >
                <template #icon><send-outlined /></template>
              </a-button>
            </a-input-group>
            <div class="attached-files" v-if="fileList.length > 0">
              <div class="file-list">
                <div v-for="(file, index) in fileList" :key="index" class="file-item">
                  <a-space>
                    <file-outlined />
                    <span class="file-name">{{ file.name }}</span>
                    <a-button type="text" size="small" @click="removeFile(index)" class="remove-btn">
                      <template #icon><close-outlined /></template>
                    </a-button>
                  </a-space>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 文件上传模态框 -->
        <!-- <a-modal
          v-model:visible="uploadModalVisible"
          title="上传文件"
          @ok="handleUploadOk"
        >
          <div class="upload-container">
            <a-upload
              v-model:file-list="fileList"
              :multiple="true"
              action="/api/upload"
              @change="handleUploadChange"
            >
              <div class="upload-content">
                <p class="upload-icon"><cloud-upload-outlined /></p>
                <p class="upload-text">Upload files</p>
                <p class="upload-hint">Click or drag files to this area to upload</p>
              </div>
            </a-upload>
          </div>
        </a-modal> -->
      </div>
    </div>
  </div>
</template>

<script setup name="aiChat">
import { ref, onMounted, h } from 'vue'
import {
  PlusOutlined,
  RobotOutlined,
  ShareAltOutlined,
  EllipsisOutlined,
  FireOutlined,
  ReadOutlined,
  CloudUploadOutlined,
  HeartOutlined,
  AimOutlined,
  SmileOutlined,
  SendOutlined,
  PaperClipOutlined,
  FileOutlined,
  CloseOutlined,
  DeleteOutlined,
  UserOutlined
} from '@ant-design/icons-vue'
import {Bubble, BubbleList} from 'ant-design-x-vue'
import aiChatRecordApi from '@/api/ai/aiChatRecordApi'
import aiChatApi from '@/api/ai/aiChatApi'

// 状态变量
const loading = ref(false)
const messagesLoading = ref(false)
const sending = ref(false)
const inputMessage = ref('')
const currentChatId = ref(null)
const messageContainer = ref(null)
const activeTabKey = ref('input')
const fileList = ref([])
const showTopicGuides = computed(() => currentMessages.value.length === 0)  // 控制快捷主题和设计指南区域的显示
const uploadModalVisible = ref(false) // 控制上传模态框的显示

// 气泡角色配置
const roles = {
  ai: {
    placement: 'start',
    avatar: { icon: h(RobotOutlined), style: { background: '#fde3cf' } },
    style: {
      maxWidth: '600px',
    },
	  // 增加打印机
	typing:{ step: 2, interval: 50 }
  },
  user: {
    placement: 'end',
    avatar: { icon: h(UserOutlined), style: { background: '#87d068' } },
  },
}

// 会话列表
const chatList = ref([])

// 当前会话消息
const currentMessages = ref([])

// Hot Topics 数据
const hotTopics = ref([
  { id: 1, title: "What's new in X?" },
  { id: 2, title: "What's AGI?" },
  { id: 3, title: "Where is the doc?" }
])

// Design Guide 数据
const designGuides = ref([
  { id: 1, title: "How to design a good product?", icon: ReadOutlined },
  { id: 2, title: "Know the well", icon: HeartOutlined },
  { id: 3, title: "Set the AI role", icon: AimOutlined },
  { id: 4, title: "Express the feeling", icon: SmileOutlined }
])

// 创建新会话
const createNewChat = async () => {
  const sessionId = Date.now().toString()
  const newChat = {
    sessionId: sessionId,
    title: '新会话',
    lastMessage: '',
    createTime: new Date()
  }
  chatList.value.unshift(newChat)
  switchChat(newChat)
}

// 删除会话
const deleteChat = async (chat) => {
  try {
    await aiChatApi.deleteSession(chat.sessionId)
    // 从列表中移除该会话
    chatList.value = chatList.value.filter(item => item.sessionId !== chat.sessionId)
    // 如果删除的是当前会话，清空当前消息
    if (currentChatId.value === chat.sessionId) {
      currentChatId.value = null
      currentMessages.value = []
    }
    // 如果删除后没有会话了，创建一个新的会话
    if (chatList.value.length === 0) {
      createNewChat()
    }
  } catch (error) {
    console.error('删除会话失败:', error)
  }
}

// 切换会话
const switchChat = async (chat) => {
  currentChatId.value = chat.sessionId
  messagesLoading.value = true

  try {
    // 获取会话消息记录
    const result = await aiChatApi.getMessages(chat.sessionId)
    if (result) {
      currentMessages.value = result
      scrollToBottom()
    }
  } catch (error) {
    console.error('获取会话消息失败:', error)
    currentMessages.value = []
  } finally {
    messagesLoading.value = false
  }
}

// 选择热门话题
const selectTopic = (topic) => {
  inputMessage.value = topic.title
  showTopicGuides.value = false  // 隐藏快捷主题和设计指南区域
  sendMessage()
}

// 选择设计指南
const selectGuide = (guide) => {
  inputMessage.value = guide.title
  showTopicGuides.value = false  // 隐藏快捷主题和设计指南区域
  sendMessage()
}



// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || sending.value) return

  showTopicGuides.value = false  // 隐藏快捷主题和设计指南区域

  const message = {
    role: 'user',
    content: inputMessage.value.trim(),
    timestamp: Date.now()
  }

  // 添加用户消息到UI
  currentMessages.value.push(message)
  scrollToBottom()

  // 更新当前会话的最后消息
  const currentChat = chatList.value.find(chat => chat.sessionId === currentChatId.value)
  if (currentChat) {
    currentChat.lastMessage = message.content
  }

  sending.value = true
  const userMessage = inputMessage.value.trim()
  inputMessage.value = ''

  try {
    // 创建AI回复的占位消息
    const aiMessage = {
      role: 'assistant',
      content: '',
      timestamp: Date.now()
    }
    currentMessages.value.push(aiMessage)
	  const messageIndex = currentMessages.value.length - 1  // 直接记录索引位置

    // 调用后端API发送消息，处理流式响应
    const eventSource = aiChatApi.sendMessage({
      message: userMessage,
      sessionId: currentChatId.value
    },
    // 处理流式响应
    (partialResponse) => {
      // console.log('页面获取到流式响应:', partialResponse)
      // 直接通过记录的索引更新消息内容
      currentMessages.value[messageIndex].content += partialResponse
      // 强制触发响应式更新
      currentMessages.value = [...currentMessages.value]
      // console.log('更新AI回复:', partialResponse, '当前完整内容:', currentMessages.value[messageIndex].content)
      scrollToBottom()
    },
    // 处理错误
    (error) => {
      console.error('流式响应错误:', error)
    })
  } catch (error) {
    console.error('发送消息失败:', error)
  } finally {
    scrollToBottom()
    sending.value = false
  }
}

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
  }, 100)
}

// 加载会话列表
const loadChatSessions = async () => {
  loading.value = true
  try {
    const sessions = await aiChatApi.getSessions()
    if (sessions && sessions.length > 0) {
      chatList.value = sessions
      // 默认选择第一个会话
      switchChat(sessions[0])
    } else {
      // 如果没有会话，创建一个新的
      createNewChat()
    }
  } catch (error) {
    console.error('获取会话列表失败:', error)
    createNewChat()
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载会话列表
onMounted(() => {
  loadChatSessions()
})</script>
<style lang="less" scoped>
.chat-container {
  display: flex;
  height: 100%;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;

  .chat-sidebar {
    width: 280px;
    border-right: 1px solid rgba(0, 0, 0, 0.06);
    background: #ffffff;
    display: flex;
    flex-direction: column;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .sidebar-content {
      height: 100%;
      overflow: hidden;

      .chat-list-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        background: #ffffff;
        border-bottom: 1px solid rgba(0, 0, 0, 0.06);

        .header-title {
          font-size: 16px;
          font-weight: 500;
          color: #262626;
        }
      }

      .chat-list {
        height: 100%;
        overflow-y: auto;
        padding: 8px 0;

        :deep(.ant-list-item) {
          padding: 12px 16px;
          cursor: pointer;
          transition: all 0.3s;
          border: none;
          margin: 6px 8px;
          border-radius: 8px;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
          background: #fafafa;

          &:hover {
            background: #f0f7ff;
            transform: translateY(-1px);
            box-shadow: 0 2px 6px rgba(24, 144, 255, 0.1);
          }

          &.active {
            background: #e6f7ff;
            border-left: 3px solid #1890ff;
          }

          .chat-title {
            color: #262626;
            font-weight: 500;
            margin-bottom: 4px;
          }

          .chat-message {
            color: #8c8c8c;
            font-size: 12px;
          }

          .delete-btn {
            opacity: 0;
            transition: opacity 0.3s;
            color: #bfbfbf;

            &:hover {
              color: #ff4d4f;
            }
          }

          &:hover .delete-btn {
            opacity: 1;
          }
        }
      }
    }
  }

  .chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;

    .chat-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 24px;
      border-bottom: 1px solid #f0f0f0;

      .chat-title {
        .title-content {
          h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 500;
          }

          .subtitle {
            margin: 0;
            color: #8c8c8c;
            font-size: 14px;
          }
        }

        .ai-avatar {
          background-color: #1890ff;
          color: #fff;
        }
      }

      .header-actions {
        .share-btn, .more-btn {
          font-size: 18px;
        }
      }
    }

    .chat-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      padding: 20px;

      .topic-tabs {
        margin-bottom: 20px;

        .do-you-want {
          font-size: 18px;
          font-weight: 500;
          margin-bottom: 20px;
        }

        .topic-section {
          background: #f9f9f9;
          border-radius: 8px;
          padding: 16px;
          margin-bottom: 16px;

          .topic-header {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
            margin-bottom: 12px;
            font-size: 16px;
          }

          .topic-content {
            .topic-item {
              cursor: pointer;
              border-radius: 4px;
              transition: background-color 0.3s;

              &:hover {
                background-color: #f0f0f0;
              }
            }
          }
        }
      }

      .chat-messages {
        flex: 1;
        overflow-y: auto;
        margin-bottom: 20px;

        .message-item {
          margin-bottom: 20px;

          .message-content {
            display: flex;
            align-items: flex-start;
            gap: 12px;

            .content {
              background: #f5f5f5;
              padding: 12px 16px;
              border-radius: 8px;
              max-width: 80%;
            }
          }

          &.assistant .message-content {
            .content {
              background: #e6f7ff;
            }
          }
        }
      }

      .chat-bottom {
        .quick-actions {
          margin-bottom: 12px;
          padding: 0 8px;

          .ant-btn {
            color: #595959;

            &:hover {
              color: #1890ff;
              background: rgba(24, 144, 255, 0.1);
            }
          }
        }

        .chat-input {
          border: 1px solid #f0f0f0;
          border-radius: 8px;
          padding: 8px 12px;
          background-color: #fff;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
          margin: 0 16px 16px;

          .input-tools {
            display: flex;
            justify-content: space-between;
            padding: 4px 0;
            border-bottom: 1px solid #f5f5f5;
            margin-bottom: 8px;

            .tool-btn {
              color: #595959;
              padding: 4px 8px;

              &:hover {
                color: #1890ff;
                background: rgba(24, 144, 255, 0.1);
              }
            }
          }

          .input-group {
            display: flex;
            align-items: flex-end;
            gap: 8px;

            .message-input {
              flex: 1;
              resize: none;
              padding: 8px 0;

              &:focus {
                box-shadow: none;
              }
            }

            .send-button {
              margin-bottom: 8px;
            }
          }

          .attached-files {
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid #f5f5f5;

            .file-list {
              .file-item {
                padding: 4px 8px;
                background: #f9f9f9;
                border-radius: 4px;
                margin-bottom: 4px;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .file-name {
                  flex: 1;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  margin: 0 8px;
                  font-size: 12px;
                }

                .remove-btn {
                  padding: 0 4px;
                  color: #999;

                  &:hover {
                    color: #ff4d4f;
                  }
                }
              }
            }
          }
        }

        .attachments-area {
          padding: 20px;

          .upload-container {
            border: 1px dashed #d9d9d9;
            border-radius: 8px;
            background: #fafafa;
            text-align: center;
            padding: 32px;
            cursor: pointer;
            transition: border-color 0.3s;

            &:hover {
              border-color: #1890ff;
            }

            .upload-content {
              .upload-icon {
                font-size: 48px;
                color: #1890ff;
                margin-bottom: 8px;
              }

              .upload-text {
                font-size: 16px;
                font-weight: 500;
                margin-bottom: 8px;
              }

              .upload-hint {
                color: #8c8c8c;
              }
            }
          }
        }

        .tab-buttons {
          display: flex;
          justify-content: center;
          padding: 8px 0 16px;

          .tab-btn {
            padding: 4px 12px;
            border-radius: 16px;

            &.active {
              background: #f0f0f0;
            }
          }
        }
      }
    }
  }
}
</style>
